//
//  ZCOrderCheckVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/2/27.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCOrderCheckVC.h"

#import "ZCOrderCheckAddressCell.h"
#import "ZCOrderCheckSectionHeadView.h"
#import "ZCOrderCheckGoodsInfoCell.h"
#import "ZCOrderCheckInputMsgCell.h"
#import "ZCOrderCheckLeftAndRightCell.h"
#import "ZCOrderCheckLeftAndSwCell.h"
#import "ZCOrderCheckAutoCell.h"
#import "ZCOrderCheckAddAddressCell.h"
#import "WZGOrderCheckReturnNoWorryCell.h"
#import "WZGOrderCheckSubtotalCell.h"

#import "WZGAddressListVC.h"

#import "ZCOrderPayVC.h"
#import "ZCOrderViewModel.h"

#import "ZCOrderChoiseCouponVC.h"
#import "ZCAddNewAddressVC.h"
#import "WZGConvertSuccessVC.h"

#import "ZCOrderChoiseCouponVC.h"
#import "PaymentManager.h"

#import "WZGShowNoworryView.h"
#import "ZCWebVC.h"
#import "WZGOrderCheckItemModel.h"
#import "WZGProtocolModel.h"
#import "WZGProtocolListViewModel.h"
#import "WZGAddressModel.h"
#import <Masonry.h>
#import <MJExtension.h>
#import <BlocksKit+UIKit.h>
#import "WZGOrderComitCheckView.h"

@interface ZCOrderCheckVC ()
@property (nonatomic, copy) NSDictionary *result;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bar;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;
@property (nonatomic, strong) UIButton *convertBtn;

@property (nonatomic, copy) NSDictionary *couponDict;
@property (nonatomic, strong) NSMutableArray *payitems;
@property (nonatomic, strong) NSMutableArray *goodsArray ;

@property (assign, nonatomic) BOOL chooseInsurance_fee;

@property (nonatomic, copy) NSString *groupSn;

@property (nonatomic, strong) NSMutableArray *chooseInsuranceArray ;

@property (nonatomic, strong) WZGOrderCheckItemModel *checkModel ;
@property (nonatomic, assign) CGFloat total_actual_fee ;
@property (nonatomic, assign) CGFloat coupon_fee ;//选择的优惠券

@property (nonatomic, strong) NSMutableArray *protocolArray ;

@property (nonatomic, strong) WZGAddressModel  *currentAddrModel ;

@end

@implementation ZCOrderCheckVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.coupon_fee = 0.0f;
    self.chooseInsurance_fee = false;
    [self setupUI];
    [self netFetchGoodsCoupon];
    [self netFetchProtocol];
}

- (void)setupUI {
  self.view.backgroundColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xf8f8f8"];
    self.navTitle = @"确认订单";
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.bar.layer.shadowColor = [UIColor grayColor].CGColor;
    self.bar.layer.shadowOffset = CGSizeMake(0, -2);
    self.bar.layer.shadowOpacity = 0.5;

    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckAddressCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckAddressCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckGoodsInfoCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckGoodsInfoCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckInputMsgCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckInputMsgCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckLeftAndRightCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckLeftAndRightCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckLeftAndRightCell" bundle:nil] forCellReuseIdentifier:@"couponCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WZGOrderCheckReturnNoWorryCell" bundle:nil] forCellReuseIdentifier:@"WZGOrderCheckReturnNoWorryCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WZGOrderCheckSubtotalCell" bundle:nil] forCellReuseIdentifier:@"WZGOrderCheckSubtotalCell"];
    self.tableView.hidden = YES;
    //
    UIView *footv = [UIView new];
    self.tableView.tableFooterView = footv;
    self.commitBtn.backgroundColor = [UIColor redColor];
    
    if (self.is_coupon_convert) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:@"确认兑换" forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.backgroundColor = [UIColor redColor];
        [self.view addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(0);
            if (@available(iOS 11.0, *)) {
                make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.bottom.mas_equalTo(0);
            }
            make.height.mas_equalTo(self.bar.mas_height);
        }];
        self.convertBtn = btn;
        [btn bk_addEventHandler:^(id sender) {
            id coupon =  [self.result valueForKey:@"coupon"];
            if ([coupon isKindOfClass:[NSArray class]]) {
                if ([(NSArray *)coupon count] == 0) {
                    [self.view makeToast:@"请选择优惠券" duration:2.0 position:CSToastPositionCenter];
                    return;
                }
            } else {
                if ([[coupon allKeys] count] == 0) {
                    [self.view makeToast:@"请选择优惠券" duration:2.0 position:CSToastPositionCenter];
                    return;
                }
                [self postOrderBtnClickAction:nil];
            }
        } forControlEvents:UIControlEventTouchUpInside];
    }
}

// MARK: - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.goodsArray.count+2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section==0) {
         return 1;
    }else if(section == self.goodsArray.count+1){
        return 2;
    }else{
        WZGOrderCheckItemModel *model = [self.goodsArray objectAtIndex:section-1];
        return 5+model.items.count;
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    WeakSelf(self);
    if (section==0) {
        ZCOrderCheckAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckAddressCell"];
       
        [cell setAddressModel:self.currentAddrModel];
         return cell;
    }else if(section == self.goodsArray.count+1){
        if (row==0) {
            ZCOrderCheckLeftAndRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"couponCellId"];
            cell.keystr = @"优惠券";
            NSInteger coupon_total = [[self.couponDict valueForKey:@"coupon_total"] integerValue];
            if (coupon_total >= 1) {
                cell.canMore = YES;
                if (weakself.coupon_fee>0) {
                    cell.valuestr = [NSString stringWithFormat:@"优惠券抵扣￥%0.1f",weakself.coupon_fee];
                }else{
                    cell.valuestr = [NSString stringWithFormat:@"%zd张可用",coupon_total];
                }
            } else {
                cell.valuestr = @"暂无可用优惠券";
                cell.canMore = NO;
            }
            return cell;
        }
        if (row == 1) {
            WZGOrderCheckReturnNoWorryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGOrderCheckReturnNoWorryCell"];
            cell.rLabel.text = @"全选";
            cell.tipLabel.hidden = YES;
            cell.detailBtn.hidden = YES;
            [cell setChooseClickBlock:^{
                weakself.chooseInsurance_fee = !weakself.chooseInsurance_fee;
                weakself.total_actual_fee = [[weakself.result valueForKey:@"actual_fee"] floatValue];
                if (weakself.chooseInsurance_fee) {
                    for (WZGOrderCheckItemModel* m in weakself.goodsArray) {
                        m.choosen = YES;
                        weakself.total_actual_fee += m.insurance_fee;
                    }
                }else{
                    for (WZGOrderCheckItemModel* m in weakself.goodsArray) {
                        m.choosen = NO;
                    }
                }
                [weakself updateBarUI:weakself.total_actual_fee];
                if (@available(iOS 11.0, *)) {
                    NSInteger sections = [tableView numberOfSections];
                    [tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, sections-1)] withRowAnimation:UITableViewRowAnimationNone];
                } else {
                    [tableView reloadData];
                }
                
            }];
            [cell setChooseAll:self.chooseInsurance_fee];
            return cell;
        }
    }else{
        //先取出商品
        WZGOrderCheckItemModel* model = self.goodsArray[section-1];
        //下单立减
        CGFloat diff_fee = model.diff_fee;
        //运费
        CGFloat freight_fee = model.freight_fee;
        //退换省心
        CGFloat insurance_fee = model.insurance_fee;
        //价格
        CGFloat price = 0.0;
        NSInteger count = model.items.count;
        if (row < count) {
            ZCOrderCheckGoodsInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckGoodsInfoCell" forIndexPath:indexPath];
            
            cell.dict = [model.items[row] mj_keyValues];
            return cell;
        }else{
            if (row==count) {
                ZCOrderCheckLeftAndRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckLeftAndRightCell"];
                cell.canMore = NO;
                cell.keystr = @"下单立减";
                
                cell.valuestr = [NSString stringWithFormat:@"￥%.2f",diff_fee];
                return cell;
            }
            
            if (row == count +1) {
                ZCOrderCheckLeftAndRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckLeftAndRightCell"];
                    cell.canMore = NO;
                    cell.keystr = @"运费";
                    
                    cell.valuestr = freight_fee > 0 ? [NSString stringWithFormat:@"￥%.2f",freight_fee] : @"包邮";
                
                    return cell;
            }
            
            if (count+2 == row) {
                WZGOrderCheckReturnNoWorryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGOrderCheckReturnNoWorryCell"];
                WZGProtocolModel *protocol = [weakself.protocolArray firstObject];
                cell.rLabel.text = [NSString stringWithFormat:@"￥%.2f",insurance_fee];
                if (protocol.protocol_name.length==0) {
                    cell.tipLabel.hidden = YES;
                    cell.detailBtn.hidden = YES;
                }else{
                    cell.tipLabel.hidden = NO;
                    cell.detailBtn.hidden = NO;
                    cell.tipLabel.text = [NSString stringWithFormat:@"《%@》",protocol.protocol_name];
                }
                [cell setDetailClickBlock:^{
                    if (protocol.is_pop_up.intValue) {
                        [WZGShowNoworryView showView:protocol WithComplete:^{
                            //去看完整条约
                            ZCWebVC *vc = [[ZCWebVC alloc] init];
                            vc.navTitle = protocol.protocol_name;
                            vc.htmlstr = protocol.protocol_content;
                            [weakself.navigationController pushViewController:vc animated:YES];
                        }];
                    }else{
                        //去看完整条约
                        ZCWebVC *vc = [[ZCWebVC alloc] init];
                        vc.navTitle = protocol.protocol_name;
                        vc.htmlstr = protocol.protocol_content;
                        [weakself.navigationController pushViewController:vc animated:YES];
                    }
                }];
                [cell setChooseClickBlock:^{
                    NSLog(@"choose---------");
                    model.choosen = !model.choosen;
                    //如果所有都选中就是全选
                    int cnt = 0;
                    if (model.choosen) {
                        for (WZGOrderCheckItemModel* m in weakself.goodsArray) {
                            if (m.choosen) {
                                cnt++;
                            }
                        }
                        if (cnt==weakself.goodsArray.count) {
                            weakself.chooseInsurance_fee = YES;
                        }else{
                            weakself.chooseInsurance_fee = NO;
                        }
                    }else{
                        for (WZGOrderCheckItemModel* m in weakself.goodsArray) {
                            if (!m.choosen) {
                                cnt++;
                            }
                        }
                        weakself.chooseInsurance_fee = NO;
                    }
                    
                    if (model.choosen) {
                        weakself.total_actual_fee += model.insurance_fee;
                    }else{
                        weakself.total_actual_fee -= model.insurance_fee;
                    }
                    [weakself updateBarUI:weakself.total_actual_fee];
                    if (@available(iOS 11.0, *)) {
                        NSInteger sections = [tableView numberOfSections];
                        [tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, sections-1)] withRowAnimation:UITableViewRowAnimationNone];
                    } else {
                        [tableView reloadData];
                    }
                }];
                
                cell.chooseAll = model.choosen;
                cell.tipLabel.hidden = YES;
                return cell;
            }
            
            if (row == count+3) {
                ZCOrderCheckInputMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckInputMsgCell" forIndexPath:indexPath];
                [cell setContentStr:model.buyer_message];
                [cell setEndEditCallback:^(NSString *txt) {
                    model.buyer_message = txt;
                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                }];
                return cell;
            }
            
            if (row == count+4) {
                WZGOrderCheckSubtotalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGOrderCheckSubtotalCell" forIndexPath:indexPath];
                //actual_fee 实际价格是除开退换省心价格之外的 后端算好之后的商品要支付的价格
                price = model.actual_fee;

                CGFloat total = price;
                if (model.choosen) {
                    total += insurance_fee;
                }
                cell.subTotalLabel.text = [NSString stringWithFormat:@"￥%0.2f",total];
                return cell;
            }
        }
        
    }
   
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    // 圆角角度
    CGFloat radius = 8.f;
    // layer
    CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
    // 获取显示区域大小
    CGRect bounds = CGRectInset(cell.bounds, 0, 0);
    // 获取每组行数
    NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
    // 贝塞尔曲线
    UIBezierPath *bezierPath = nil;
    
    if (rowNum == 1) {
        // 一组只有一行（四个角全部为圆角）
        bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                           byRoundingCorners:UIRectCornerAllCorners
                                                 cornerRadii:CGSizeMake(radius, radius)];
    } else {
        if (indexPath.row == 0) {
            // 每组第一行（添加左上和右上的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                               byRoundingCorners:(UIRectCornerTopLeft|UIRectCornerTopRight)
                                                     cornerRadii:CGSizeMake(radius, radius)];
            
        } else if (indexPath.row == rowNum - 1) {
            // 每组最后一行（添加左下和右下的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds
                                               byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight)
                                                     cornerRadii:CGSizeMake(radius, radius)];
        } else {
            // 每组不是首位的行不设置圆角
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
    }
    // 把已经绘制好的贝塞尔曲线路径赋值给图层，然后图层根据path进行图像渲染render
    normalLayer.path = bezierPath.CGPath;
    normalLayer.frame = cell.bounds;
    cell.layer.mask = normalLayer;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 190.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    NSInteger cross_border = [[self.result valueForKey:@"cross_border"] integerValue];
    //选择地址
    if (section == 0) {
        WZGAddressListVC *vc = [[WZGAddressListVC alloc] init];
        vc.isNormal = cross_border != 1;
        vc.canselect = YES;
        __weak typeof(self) weakSelf = self;
        [vc setAddressSelectedCallBack:^(NSDictionary * _Nonnull dict ,bool isChanged){
            if(dict != nil) {
                WZGAddressModel *addressModel = [WZGAddressModel mj_objectWithKeyValues:dict];
                if (isChanged) {
                    if ([weakSelf.currentAddrModel.idstr isEqualToString:addressModel.idstr]) {
                        [weakSelf netFetchOrderCheckInfoWithInfo:weakSelf.dict];
                        weakSelf.chooseInsurance_fee = NO;
                    }else{
                        weakSelf.currentAddrModel = addressModel;
                        [weakSelf.tableView reloadData];
                    }
                }else{
                    weakSelf.currentAddrModel = addressModel;
                    [weakSelf.tableView reloadData];
                }
            }else{
                if (isChanged) {
                    [weakSelf netFetchOrderCheckInfoWithInfo:weakSelf.dict];
                }
            }
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    if (section == self.goodsArray.count+1) {
        if (indexPath.row==1) {
            return;
        }
        NSInteger coupon_total = [[self.couponDict valueForKey:@"coupon_total"] integerValue];
        if (coupon_total<=0) {
            return;
        }
        // 跳至选择优惠券页面
        ZCOrderChoiseCouponVC *vc = [[ZCOrderChoiseCouponVC alloc] init];
        vc.selectId = [self.dict valueForKey:@"coupon_id"];
        vc.list = [self.couponDict valueForKey:@"coupon"];
        __weak typeof(self) weakSelf = self;
        [vc setBtnClickCallback:^(NSDictionary *dict) {
            if (dict != nil) {
                NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:weakSelf.dict];
                [mdict setValue:[dict valueForKey:@"id"] forKey:@"coupon_id"];
                weakSelf.dict = mdict.copy;
                NSDictionary *coupon = [dict valueForKey:@"coupon"];
                weakSelf.coupon_fee = [[coupon valueForKey:@"money"] floatValue];
                if (weakSelf.total_actual_fee-weakSelf.coupon_fee<0) {
                    [weakSelf.view makeToast:@"不能使用优惠券" duration:1 position:CSToastPositionCenter];
                    return ;
                }
                weakSelf.total_actual_fee -= weakSelf.coupon_fee;
                [weakSelf updateBarUI:weakSelf.total_actual_fee];
                [weakSelf netFetchOrderCheckInfoWithInfo:mdict];
            } else {
                NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:weakSelf.dict];
                [mdict removeObjectForKey:@"coupon_id"];
                weakSelf.dict = mdict.copy;
                [weakSelf netFetchOrderCheckInfoWithInfo:mdict];
                weakSelf.coupon_fee = 0;
            }
        }];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)updateBarUI:(CGFloat)total_fee {
    NSString *str = [NSString stringWithFormat:@"￥%.2f",total_fee];
    NSMutableAttributedString *mstr = [[NSMutableAttributedString alloc] initWithString:str];
    [mstr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]} range:(NSRange){0,1}];
    [mstr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} range:(NSRange){1,str.length - 1}];
    self.priceLabel.attributedText = mstr;
}

// MARK: - Action
// MARK: - 提交订单
- (IBAction)postOrderBtnClickAction:(id)sender {
    NSInteger cross_border = [[self.result valueForKey:@"cross_border"] integerValue];
    
    NSString *id_card = nil;
    if (self.currentAddrModel) {
        id_card = self.currentAddrModel.id_card;
        NSMutableDictionary *mdict = self.dict.mutableCopy;
        [mdict setValue:self.currentAddrModel.idstr forKey:@"address_ids"];
        self.dict = mdict.copy;
    }
    
    if ([self.dict valueForKey:@"address_ids"] == nil) {
        [self.view makeToast:@"请先选择收货地址" duration:2.0 position:CSToastPositionCenter];
        return;
    }
    if ((id_card == nil || id_card.length == 0) && cross_border == 1) {
        [self showAlert:@"提示" content:@"当前订单存在跨境商品，需要填写收货人真实姓名和身份证" actionStr1:@"确定" style:UIAlertActionStyleDefault actionAc1:^(UIAlertAction * _Nonnull action) {
            ZCAddNewAddressVC *vc = [[ZCAddNewAddressVC alloc] init];
            vc.isNormal = NO;
            vc.dict = [self.currentAddrModel mj_keyValues];
            [self.navigationController pushViewController:vc animated:YES];
        } actionStr2:@"取消" style:UIAlertActionStyleCancel actionAc:^(UIAlertAction * _Nonnull action) {
            
        }];
        return;
    }
    
    WeakSelf(self);
    NSMutableDictionary *viewDict = [NSMutableDictionary dictionary];
    /*
     1.商品的种类 goodsItems
     2.计数 几件 --- 通过计算
     3.商品总价 --- 通过计算得出总价
     4.运费 --- 通过计算得出
     5.退换省心 --- 通过计算得出
     6.优惠券
     7.实付款
     */
    
    [viewDict setObject:self.currentAddrModel forKey:@"address"];//地址
    [viewDict setObject:self.goodsArray forKey:@"goods"];//商品的种类
    [viewDict setObject:@(self.coupon_fee).stringValue forKey:@"coupon_fee"];//优惠券
    [viewDict setObject:@(self.total_actual_fee).stringValue forKey:@"total_actual_fee"];//实付款
    
    [WZGOrderComitCheckView showViewOnView:nil withData:viewDict completion:^(NSInteger type) {
        if (type == 1) {
            [weakself netCommitOrderWithInfo:weakself.dict];
        }
    }];
    
}

- (void)loadConvertSuccessVC {
    WZGConvertSuccessVC *vc = [[WZGConvertSuccessVC alloc] init];
    NSMutableArray *vcs = self.navigationController.childViewControllers.mutableCopy;
    [vcs replaceObjectAtIndex:vcs.count - 1 withObject:vc];
    [self.navigationController setViewControllers:vcs animated:YES];
}

- (void)loadOrderPayVCWithDict:(NSDictionary *)dict {
    NSString *order_id = [dict valueForKey:@"order_id"];
    self.groupSn = [dict valueForKey:@"group_sn"];
    ZCOrderPayVC *vc = [[ZCOrderPayVC alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.dict = dict;
    vc.groupSN = self.groupSn;
    vc.isOrderList = NO;
    NSMutableArray *vcs = self.navigationController.childViewControllers.mutableCopy;
    [vcs replaceObjectAtIndex:vcs.count - 1 withObject:vc];
    [self.navigationController setViewControllers:vcs animated:YES];
}

// MARK: - WXApiManagerDelegate

- (void)managerDidRecvMiniResponse:(WXLaunchMiniProgramResp *)response {
    switch (response.errCode) {
        case WXSuccess: {
            [self.view makeToast:@"支付成功" duration:2.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
            break;
        case WXErrCodeUserCancel: {
            [self.view makeToast:@"支付取消了" duration:2.0 position:CSToastPositionCenter];
        }
            break;
        default:{
            [self.view makeToast:@"支付失败" duration:2.0 position:CSToastPositionCenter];
        }
            break;
    }
}

- (void)setParams:(NSDictionary *)params {
  [super setParams:params];
  self.dict = [params valueForKey:@"dict"];
  [self netFetchGoodsCoupon];
  [self netFetchProtocol];
}

// MARK: - NET

- (void)netFetchGoodsCoupon {
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:[self.dict valueForKey:@"goods_id"] forKey:@"goods_id"];
    [parameters setValue:[self.dict valueForKey:@"cart_ids"] forKey:@"cart_ids"];
    [parameters setValue:[self.dict valueForKey:@"nums"] forKey:@"goods_num"];
    [parameters setValue:@(self.is_coupon_convert) forKey:@"is_coupon_convert"];
    [parameters setValue:@"1.0" forKey:@"api_version"];
    
    [SKBaseWebService getRequest:@"/v1/order/goods-coupon" parameters:parameters progress:nil success:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
            weakSelf.couponDict = data;
            [weakSelf.tableView reloadData];
            [weakSelf netFetchOrderCheckInfoWithInfo:weakSelf.dict];
    } failure:^(ZCErrorCode status, NSString *msg, NSDictionary *data) {
        if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                if (type == 0) {
//                    [weakSelf.navigationController popViewControllerAnimated:YES];
//                } else {
//                    [weakSelf netFetchGoodsCoupon];
//                }
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:msg duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netFetchOrderCheckInfoWithInfo:(NSDictionary *)info {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *mdict = info.mutableCopy;
    [mdict addEntriesFromDictionary:self.groupBuyInfo];
    [mdict setValue:@"2.0" forKey:@"api_version"];
    [ZCOrderViewModel confirmOrderWithInfo:mdict complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            weakSelf.result = data;
            
            [weakSelf.goodsArray removeAllObjects];
            
            //更新地址信息
            if (weakSelf.currentAddrModel == nil) {
                NSArray *addrArray = [data valueForKey:@"addrs"];
                NSMutableArray *addrArr = [NSMutableArray array];
                for(NSDictionary * address  in addrArray){
                    WZGAddressModel *addressModel = [WZGAddressModel mj_objectWithKeyValues:address];
                    [addrArr addObject:addressModel];
                }
                if (addrArr.count > 0) {
                    weakSelf.currentAddrModel = addrArr.firstObject;
                }else{
                    weakSelf.currentAddrModel = nil;
                }
            }

            NSDictionary* goods = [self.result valueForKey:@"goods"];
            for (NSDictionary *dict in [goods allValues]) {
                WZGOrderCheckItemModel *model = [WZGOrderCheckItemModel mj_objectWithKeyValues:dict];
                [weakSelf.goodsArray addObject:model];
            }
            
            weakSelf.total_actual_fee = [[weakSelf.result valueForKey:@"actual_fee"] floatValue];
            
            [weakSelf updateBarUI:weakSelf.total_actual_fee];
            weakSelf.tableView.hidden = NO;
            [weakSelf.tableView reloadData];
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                if (type == 0) {
//                    [weakSelf.tableView reloadData];
//                } else {
//                    [weakSelf netFetchOrderCheckInfoWithInfo:weakSelf.dict];
//                }
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}

- (void)netCommitOrderWithInfo:(NSDictionary *)info {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithDictionary:info];
    if (self.groupBuyInfo != nil) {
        [mdict addEntriesFromDictionary:self.groupBuyInfo];
    }
    if (self.liveBuyInfo != nil) {
        [mdict addEntriesFromDictionary:self.liveBuyInfo];
        [mdict setValue:@"live" forKey:@"source"];
    }
    [mdict setValue:@"2" forKey:@"api_version"];
    /*
     "goods_list": [{
         "goods_id": 2344,
         "buy_insurance": false,
         "buyer_message": "BBB"
     }, {
         "goods_id": 2511,
         "buy_insurance": false,
         "buyer_message": "AAA",
     }],
     */
    NSMutableArray *goods_list = [NSMutableArray new];
    for(int i = 0 ; i < self.goodsArray.count ; i++){
        WZGOrderCheckItemModel *model = self.goodsArray[i];
        NSDictionary *dict = @{@"goods_id":@(model.goods_id),
                               @"buy_insurance":@(model.choosen),
                               @"buyer_message":model.buyer_message?model.buyer_message:@""};
        [goods_list addObject:dict];
    }

    [mdict setValue:goods_list forKey:@"goods_list"];
    [ZCOrderViewModel commitOrderWithInfo:mdict complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"mainupshoppingnum" object:nil];
            if (weakSelf.is_coupon_convert) {
                [weakSelf loadConvertSuccessVC];
            } else {
                [weakSelf loadOrderPayVCWithDict:data];
            }
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netAutoCheckAddressWithInputTxt:(NSString *)address {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCOrderViewModel autoCheckAddressWithString:address complete:^(ZCErrorCode status, NSString *message, id data) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (status == kHXSNoError) {
            NSMutableDictionary *mdict = weakSelf.result.mutableCopy;
            [mdict setValue:@[data] forKey:@"addrs"];
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
            weakSelf.result = mdict.copy;
            [weakSelf.tableView reloadData];
        } else if (status == kHXSInvalidTokenError) {
//            WZGLoginVC *vc = [[WZGLoginVC alloc] init];
//            [vc setGoodsVCCallBack:^(NSInteger type) {
//                [weakSelf netFetchOrderCheckInfoWithInfo:weakSelf.dict];
//            }];
//            UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc];
//            nvc.modalPresentationStyle = UIModalPresentationFullScreen;
//            [weakSelf.navigationController presentViewController:nvc animated:YES completion:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netFetchProtocol {
    // TODO: implement
    WeakSelf(self);
    [WZGProtocolListViewModel netFetchProtocolsWithModuleName:@"close_account_page" success:^(ZCErrorCode status, NSString * _Nonnull msg, id  _Nonnull data) {
        if (status == kHXSNoError) {
            if ([data isKindOfClass:[NSArray class]]) {
                for (NSDictionary *dict in data) {
                    WZGProtocolModel *m = [WZGProtocolModel mj_objectWithKeyValues:dict];
                    [weakself.protocolArray addObject:m];
                }
                [weakself.tableView reloadData];
            }
        }
    } failure:^(ZCErrorCode status, NSString * _Nonnull msg, NSDictionary * _Nonnull data) {
        
    }];
}

// MARK: - GET

- (NSMutableArray *)payitems {
    if (_payitems == nil) {
        _payitems = [NSMutableArray new];
    }
    return _payitems;
}

- (NSMutableArray *)goodsArray{
    if (!_goodsArray) {
        _goodsArray = [[NSMutableArray alloc] init];
    }
    return _goodsArray;
}

- (NSMutableArray *)protocolArray{
    if (!_protocolArray) {
        _protocolArray = [[NSMutableArray alloc] init];
    }
    return _protocolArray;
}

@end
